<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="profile-avatar">
        <img :src="avatarUrl" alt="头像" class="avatar-image" /><br>
        <div style="margin-left: 100px">
          <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none" />
        <button class="change-avatar-btn" @click="triggerFileInput">修改头像</button>
        </div>
      </div>
      <ul class="profile-info">
        <li><i class="el-icon-user"></i> 登录名称：<span>{{ currentUser.username }}</span></li>
        <li><i class="el-icon-phone"></i> 手机号码：<span>{{ currentUser.phone }}</span></li>
        <li><i class="el-icon-office-building"></i> 所属地址：<span>{{ currentUser.address }}</span></li>
        <li><i class="el-icon-message"></i> 个人荣誉：<span>{{ currentUser.qualification }}</span></li>

      </ul>
    </div>
    <div class="profile-tabs">
      <el-tabs>
        <el-tab-pane label="基本资料">
          <el-form label-width="80px" :model="formData">
            <el-form-item label="用户名">
              <el-input v-model="formData.username" disabled />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="formData.phone" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="formData.address" />
            </el-form-item>
            <div class="form-actions">
              <el-button type="primary" @click="save">保存</el-button>
              <el-button @click="close">关闭</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码">
          <el-form label-width="80px" :model="passwordData">
            <el-form-item label="原密码">
              <el-input type="password" v-model="passwordData.oldPassword" />
            </el-form-item>
            <el-form-item label="新密码">
              <el-input type="password" v-model="passwordData.newPassword" />
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input type="password" v-model="passwordData.confirmPassword" />
            </el-form-item>
            <div class="form-actions">
              <el-button type="primary" @click="changePassword">保存</el-button>
              <el-button @click="close">关闭</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import {useStore} from "vuex";

let store = useStore()
const vip = ref(null);
const id = ref(null);
const avatarUrl=ref('');
const newAvatarUrl=ref('');
// 假设 localStorage 中存储的是一个 JSON 字符串
const storedData = localStorage.getItem('key');
if (storedData) {
  vip.value = JSON.parse(storedData);
  id.value = vip.value.data.consultantId; // 假设用户 ID 存储在 consultantId 中
  avatarUrl.value=vip.value.data.avatar;
  console.log(vip.value);
  console.log(id.value);
  console.log(avatarUrl.value);
}

const formData = ref({
  username: '',
  phone: '',
  address: ''
});

const passwordData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const currentUser = ref({
  username: '',
  password:'',
  phone: '',
  qualification: '',
  address: '',

});

axios.get(`http://127.0.0.1:9090/file/download2?fileName=${encodeURIComponent(avatarUrl.value)}`)
    .then((response) => {
      avatarUrl.value=`data:image/jpeg;base64,${response.data}`;
    })
    .catch((error) => {
      console.log(error);
    })


// 初始化 currentUser 的值
if (vip.value && vip.value.data) {
  currentUser.value.username = vip.value.data.username;
  currentUser.value.phone = vip.value.data.phoneNumber;
  currentUser.value.qualification = vip.value.data.qualification;
  currentUser.value.address = vip.value.data.address;
  currentUser.value.password = vip.value.data.password;
}
// 修改头像
const fileInput = ref('');
const triggerFileInput =()=>{
  fileInput.value.click();
}
// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('file', file);

  axios.post('http://127.0.0.1:9090/file/upload1', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
      .then(uploadResponse => {
        if (uploadResponse.data.code === 200) {
          newAvatarUrl.value = uploadResponse.data.data; // 获取上传后的文件 URL
          updateAvatarUrl(newAvatarUrl); // 更新头像 URL
          ElMessage.success('上传成功')
          console.log(uploadResponse.data.data);
          console.log(newAvatarUrl.value);
        } else {
          ElMessage.error('上传失败: ' + uploadResponse.data.message);
        }
      })
      .catch(error => {
        console.error('上传失败', error);
        ElMessage.error('上传失败');
      });
};

// 更新头像 URL
const updateAvatarUrl = (newAvatarUrl) => {
  axios.put("http://127.0.0.1:9090/upconsultants", {
    consultantId: id.value,
    avatar: newAvatarUrl.value,
  })
      .then(updateResponse => {
        if (updateResponse.data.code === 200) {
          avatarUrl.value = newAvatarUrl.value; // 更新头像 URL
          ElMessage.success('头像更新成功');
          store.commit('setIsupData',true)
          refreshAvatarUrl();
        } else {
          ElMessage.error('更新失败: ' + updateResponse.data.message);
        }
      })
      .catch(error => {
        console.error('更新失败', error);
        ElMessage.error('更新失败');
      });
};
//
// 回显头像
const refreshAvatarUrl = () => {
  axios.get(`http://127.0.0.1:9090/file/download2?fileName=${encodeURIComponent(avatarUrl.value)}`)
      .then(response => {
        avatarUrl.value = `data:image/jpeg;base64,${response.data}`; // 更新头像 URL
      })
      .catch(error => {
        console.error('回显失败', error);
        ElMessage.error('回显失败');
      });
};

onMounted(() => {
  // 初始化基本资料
  formData.value = { ...currentUser.value };
  loadData();
});

const loadData = () => {
  axios.get('http://127.0.0.1:9090/getconsultantsbyid?id='+id.value)
      .then(response => {
        if (response.data.code === 200) {
          const userData = response.data.data;
          console.log(userData)
          currentUser.value.username = userData.username;
          currentUser.value.phone = userData.phoneNumber;
          currentUser.value.qualification = userData.qualification;
          currentUser.value.address = userData.address;
          currentUser.value.password = userData.password;
          avatarUrl.value = userData.avatar;
          refreshAvatarUrl();
          console.log(currentUser.value)// 回显头像
        } else {
          ElMessage.error('加载用户数据失败: ' + response.data.message);
        }
      })
      .catch(error => {
        console.log('加载用户数据失败', error);
        ElMessage.error('加载用户数据失败');
      });
};
const refreshPage = () => {
  loadData(); // 重新加载数据
  ElMessage.info('正在刷新页面数据...');
};

function save() {
  // 更新用户资料
  axios.put("http://127.0.0.1:9090/upconsultants", {
    consultantId: id.value,
    phoneNumber: formData.value.phone,
    address: formData.value.address
  })
      .then(response => {
        console.log(response);
        if (response.data.code === 200) {
          ElMessage.success('基本资料已保存');
        } else {
          ElMessage.error('保存失败');
        }
      })
      .catch(error => {
        console.error('请求失败', error);
        ElMessage.error('保存失败');
      });
  currentUser.value = { ...formData.value };
}

function close() {
  // 这里可以关闭当前页面或返回上一页
}

function changePassword() {
  const { oldPassword, newPassword, confirmPassword } = passwordData.value;

  // 验证密码
  if (oldPassword !== currentUser.value.password) {
    ElMessage.error('原密码不正确');
    console.log(oldPassword.value);
    return;
  }

  if (newPassword !== confirmPassword) {
    ElMessage.error('新密码与确认密码不一致');
    return;
  }
  axios.put("http://127.0.0.1:9090/upconsultants", {
    consultantId: id.value,
    password: newPassword,
  })
      .then(response => {
        if (response.data.code === 200) {
          ElMessage.success('密码已修改'+ response.data.message);
        }
      })
      .catch(error => {
        console.error('请求失败', error);
        ElMessage.error('修改失败');
      });

  // 更新密码
  currentUser.value.password = newPassword;

}
</script>

<style scoped>
.profile-tabs {
  padding: 20px;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}
</style>
<style scoped>
.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
}

.profile-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.profile-avatar {
  text-align: center;
  margin-right: 30px;
}

.avatar-image {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.change-avatar-btn {
  display: block;
  margin-top: 10px;
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.profile-info {
  list-style: none;
  padding: 0;
  margin: 0;
}

.profile-info li {
  margin-bottom: 10px;
  font-size: 16px;
}

.profile-info i {
  margin-right: 5px;
  color: #909399;
}

.profile-tabs {
  width: 100%;
  background: #ffffff;
  border-radius: 6px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.form-actions .el-button {
  margin: 0 10px;
}
</style>
